package com.edfeff.nio.http;

import com.edfeff.bio.http.Header;
import com.edfeff.bio.http.Request;
import com.edfeff.bio.http.Response;
import com.edfeff.nio.ReactorSimpleHttpServer;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.List;

public class SocketProcessor implements Runnable {

    private final ReactorSimpleHttpServer server;
    private final SocketChannel socket;

    private NioInputBuffer inputBuffer;
    private NioOutputBuffer outputBuffer;

    private Request request;
    private Response response;

    public SocketProcessor(ReactorSimpleHttpServer server, SocketChannel socket) {
        this.server = server;
        this.socket = socket;
        this.request = new Request();
        this.response = new Response();
        this.inputBuffer = new NioInputBuffer(this.request, socket);
        this.outputBuffer = new NioOutputBuffer(this.response, socket);
    }

    @Override
    public void run() {
        try {
            inputBuffer.parseRequestLine();
            inputBuffer.parseHeaders();
            inputBuffer.parseRequestBody();
            prepareResponse();
            server.getAdapter().service(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(400);
        } finally {
            //todo
            outputBuffer.endRequest();
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void prepareResponse() {
        List<Header> headers = response.getHeaders();
        headers.add(new Header("server", "edfeff"));
    }
}
